package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.confin.AliOSSProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import com.leyou.common.exceptions.LyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class AliAuthServiceImpl implements AliAuthService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliOSSProperties ossProperties;
    @Override
    public AliOssSignatureDTO getAliSignature() {
        try {
            //签名有效时间
            long expireTime = 30;
            //计算到期时间
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            //对文件上传限制策略 如：文件大小类型
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProperties.getDir());
            // 对闲置策略做编码，转为字符串
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 计算签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            return AliOssSignatureDTO.of(ossProperties.getAccessKeyId(), ossProperties.getHost(), encodedPolicy, postSignature,expireEndTime / 1000, ossProperties.getDir());


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            throw new LyException(500 ,"签名授权异常" ,e );
        }
    }
}
